package com.tsxy.controller.administrator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsxy.common.APIResult;
import com.tsxy.common.Constants;
import com.tsxy.entity.Dict;
import com.tsxy.entity.Menu;
import com.tsxy.entity.RoleMenu;
import com.tsxy.mapper.RoleMenuMapper;
import com.tsxy.service.IDictService;
import com.tsxy.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 飞
 * @since 2022-02-17
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    private IMenuService menuService;
    @Resource
    private IDictService dictService;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    //新增或者修改
    @PostMapping
    public APIResult save(@RequestBody Menu menu){
        boolean b = menuService.saveOrUpdate(menu);
        Integer id = menu.getId();
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(1);
        roleMenu.setMenuId(id);
        roleMenuMapper.insert(roleMenu);
        return APIResult.success();
    }
    //根据id删除
    @DeleteMapping("/{id}")
    public APIResult delete(@PathVariable Integer id) {
        return APIResult.success(menuService.removeById(id));
    }
    //批量删除
    @PostMapping("/del/batch")
        public APIResult deleteBath(@RequestBody List<Integer> ids){
        return APIResult.success(menuService.removeByIds(ids));
    }
    //查询所有
    @GetMapping
    public APIResult findAll() {
        return APIResult.success(menuService.list());
    }

    //查询所有
    @GetMapping("/ids")
    public APIResult getIds() {
        return APIResult.success(menuService.list().stream().map(Menu::getId));
    }
    @GetMapping("/getAll")
    public APIResult getAll() {
        List<Menu> list = menuService.getAll();
        return APIResult.success(list);
    }
    //根据id查询
    @GetMapping("/{id}")
        public APIResult findOne(@PathVariable Integer id) {
        return APIResult.success(menuService.getById(id));
    }
    //分页查询
    @GetMapping("/page")
    public APIResult findPage(@RequestParam Integer pageNum,
                    @RequestParam Integer pageSize,
                              @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if ( ! "".equals(name)){
            queryWrapper.like("name",name);
        }
        return APIResult.success(menuService.page(new Page<>(pageNum,pageSize), queryWrapper));
    }

    @GetMapping("/icons")
    public APIResult getIcons(){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("type", Constants.DICT_TYPE_ICON);
        return APIResult.success(dictService.list(dictQueryWrapper));
    }

}

